package com.alinesno.cloud.operation.cmdb.controller.manager;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alinesno.cloud.operation.cmdb.advice.ConvertCode;
import com.alinesno.cloud.operation.cmdb.common.constants.AccountRoleEnum;
import com.alinesno.cloud.operation.cmdb.controller.BaseController;
import com.alinesno.cloud.operation.cmdb.entity.AccountEntity;
import com.alinesno.cloud.operation.cmdb.entity.MasterMachineEntity;
import com.alinesno.cloud.operation.cmdb.entity.ResourceEntity;
import com.alinesno.cloud.operation.cmdb.repository.AccountRepository;
import com.alinesno.cloud.operation.cmdb.repository.MasterMachineRepository;
import com.alinesno.cloud.operation.cmdb.repository.ResourceRepository;
import com.alinesno.cloud.operation.cmdb.web.bean.JqDatatablesPageBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResponseBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResultGenerator;

/**
 * 后台主面板
 * @author WeiXiaoJin
 * @since 2018年8月14日 下午12:58:05
 */
@Controller
@RequestMapping("/manager/")
public class ManagerAccountController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass()) ; 
	
	@Autowired
	private AccountRepository accountRepository ; 
	
	@Autowired
	private ResourceRepository resourceRepository ;
	
	@Autowired
	private MasterMachineRepository masterMachineRepository ; 

	@GetMapping("/account_list")
	public String list(Model model) {
		
		createMenus(model); 
		return WX_MANAGER+"account_list";
	}
	
	@GetMapping("/account_add")
	public String accountAdd(Model model) {
		allResource(model , null);
		
		return WX_MANAGER+"account_add";
	}

	@GetMapping("/account_modify/{id}")
	public String accountModify(Model model , @PathVariable("id") String id) {
		logger.debug("id = {}" , id);
		AccountEntity bean = accountRepository.findById(id).get() ; 
		
		model.addAttribute("bean" , bean) ; 
		allResource(model , id);
		
		return WX_MANAGER+"account_modify";
	}
	
	private void allResource(Model model , String accountId) {
		
		// 列出菜单 
		List<ResourceEntity> list = resourceRepository.findAll(Sort.by(Direction.DESC, "resourceSort")) ; 
	
		if(StringUtils.isNoneBlank(accountId)) {
			
			List<ResourceEntity> menusList = accountService.findResourceByUserId(accountId) ; 
			
			if(menusList != null && menusList.size() > 0) {
				for(ResourceEntity r : list) {
					for(ResourceEntity ur : menusList) {
						if(r.getId().equals(ur.getId())) {
							r.setFieldProp("checked");
						}
					}
				}
			}
			
		}
		model.addAttribute("resources" , list) ; 
	
		// 列出机房
		List<MasterMachineEntity> school = masterMachineRepository.findAll() ;  
		model.addAttribute("schools" , school) ; 
		
	}
	 
	
	/**
	 * 数据列表
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ConvertCode
	@ResponseBody
	@GetMapping("/account_list_data")
	public Object accountListData(Model model , JqDatatablesPageBean page) {

		JqDatatablesPageBean p = this.toPage(model, 
				page.buildFilter(AccountEntity.class , request)  , 
				accountRepository, page); 
		
		p.setData(convertData((List<AccountEntity>) p.getData())); 
		return p ; 
	}

	// 管理员代码转换
	private Object convertData(List<AccountEntity> data) {
		for(AccountEntity a : data) {
			AccountRoleEnum role = AccountRoleEnum.getStatus(a.getRolePower()) ; 
			a.setRolePower(role.getText());
		}
		return data ;
	}

	/**
	 * 保存添加
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/account_add_save" , method = RequestMethod.POST)
	public ResponseBean<String> saveAdd(Model model , AccountEntity bean , String resources , HttpServletRequest request) {
		
		// 查看是否已经存在登陆名
		AccountEntity account = accountRepository.findByLoginName(bean.getLoginName()) ; 
		if(account != null) {
			return ResultGenerator.genSuccessMessage("登陆名已存在.") ; 
		}
		
		boolean b = accountService.saveAccount(bean , resources , request.getRemoteHost()) ; 
		
		return b?ResultGenerator.genSuccessMessage("保存成功."):ResultGenerator.genFailMessage("保存失败.") ; 
	}
	
	/**
	 * 保存权限
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/account_modify_save" , method = RequestMethod.POST)
	public ResponseBean<String> saveModify(Model model , AccountEntity bean , HttpServletRequest request , String resources) {
		
		
		boolean b = accountService.modifyAccount(bean , resources , request.getRemoteHost()) ; 
		return b?ResultGenerator.genSuccessMessage("保存成功."):ResultGenerator.genFailMessage("保存失败.") ; 
	}
	 
}
